package com.sjyy.common.util;

import java.awt.image.BufferedImage;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFCell;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class RaUtil {

	/**
	 * 处理送货单日期
	 * @param date
	 * @return
	 */
	public static Date formatExcelDate(Date date){
		if(date.getHours()<6){
			return date;
		}
		else
			return formatDate(1,date,0,0,0);
	}
	/**
	 * 判断是否为同一天
	 * @param day1 
	 * @param day2
	 * @return
	 */
	public static boolean isSameDay(Date day1, Date day2) {

	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    String ds1 = sdf.format(day1);
	    String ds2 = sdf.format(day2);
	    if (ds1.equals(ds2)) {
	        return true;
	    } else {
	        return false;
	    }
	}
	
	/**
	 * 处理今日日期（导出订单使用）
	 * @param day
	 * @param date
	 * @return
	 */
	public static Date formatToday(int day,Date date)
	{
		Date today = new Date();//取时间 
		Calendar cal = Calendar.getInstance();
		cal.setTime(today);
		
		if(today.getHours()<3){
			if(day <=0 )
				cal.add(Calendar.DATE, day);
			else
				cal.add(Calendar.DATE, day - 1);
		}
		else
			cal.add(Calendar.DATE, day);
		
		today = cal.getTime();
		
		today.setHours(date.getHours());
		today.setMinutes(date.getMinutes());
		today.setSeconds(0);
		
		return today;
	}
	
	/**
	 * 处理日期
	 * @param day
	 * @param date
	 * @return
	 */
	public static Date formatDate(int day,Date date,int hour,int minute,int second){
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DATE, day);
		date = cal.getTime();
		
		date.setHours(hour);
		date.setMinutes(minute);
		date.setSeconds(second);
		
		return date;
	}
	
	/**
	 * MD5加密
	 * @param plainText
	 * @return 
	 */
	public static String md5(String plainText ) { 
		try { 
			MessageDigest md = MessageDigest.getInstance("MD5"); 
			md.update(plainText.getBytes()); 
			byte b[] = md.digest(); 

			int i; 

			StringBuffer buf = new StringBuffer(""); 
			for (int offset = 0; offset < b.length; offset++) { 
				i = b[offset]; 
				if(i<0) 
					i+= 256; 
				if(i<16) 
					buf.append("0"); 
				buf.append(Integer.toHexString(i)); 
			} 

			return buf.toString();
		} catch (NoSuchAlgorithmException e) { 
			// TODO Auto-generated catch block 
			e.printStackTrace(); 
		} 
		
		return "";
	} 
	
	/**
	 * 判断是否存在空格
	 * @param str
	 * @return
	 */
	public static boolean checkBlank(String str){      
        Pattern pattern = Pattern.compile("[\\s]+");
        Matcher matcher = pattern.matcher(str);
        boolean flag = false;
        while (matcher.find()) {
            flag = true;
        }
        return flag;
	}
	
	
	
	/**
	 * 判断两天相差多少
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int getQuot(Date date1, Date date2){
		  long quot = 0;

		  date1 = formatDate(0,date1,0,0,0);
		  date2 = formatDate(0,date2,0,0,0);
		  try {
		   quot = date1.getTime() - date2.getTime();
		   quot = quot / 1000 / 60 / 60 / 24;
		  } catch (Exception e) {
		   e.printStackTrace();
		  }
		  return (int)quot;
	}
	
	//获得当天0点时间 
	public static Date getTimesmorning(Date date){ 
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 0); 
		cal.set(Calendar.SECOND, 0); 
		cal.set(Calendar.MINUTE, 0); 
		cal.set(Calendar.MILLISECOND, 0); 
		return new Date(cal.getTimeInMillis()); 
	} 
	//获得当天24点时间 
	public static Date getTimesnight(Date date){ 
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 23); 
		cal.set(Calendar.SECOND, 59); 
		cal.set(Calendar.MINUTE, 59); 
		cal.set(Calendar.MILLISECOND, 999); 
		return new Date(cal.getTimeInMillis());
	}
	
	/** 
     * 根据起始日期和间隔时间计算结束日期 
     *  
     * @param sDate开始时间 
     *  
     * @param days间隔时间 
     *  
     * @return 结束时间 
     * */  
    public static Date calculateEndDate(Date sDate, int days)  
    {  
        //将开始时间赋给日历实例  
        Calendar sCalendar = Calendar.getInstance();  
        sCalendar.setTime(sDate);  
        //计算结束时间  
        sCalendar.add(Calendar.DATE, days);  
        //返回Date类型结束时间  
        return sCalendar.getTime();  
    }  
    
    /** 
     * 根据起始日期和间隔时间计算结束日期 
     *  
     * @param sDate开始时间 
     *  
     * @param hours 间隔小时
     *  
     * @return 结束时间 
     * */  
    public static Date calculateOffsetDate(Date sDate, int hours)  
    {  
        //将开始时间赋给日历实例  
        Calendar sCalendar = Calendar.getInstance();  
        sCalendar.setTime(sDate);  
        //计算结束时间  
        sCalendar.add(Calendar.HOUR, hours);  
        //返回Date类型结束时间  
        return sCalendar.getTime();  
    }
    
    //截取公告字符串
    public static String regexTagSubstr(String target,String start,String end){
    	String result = "";
    	
    	int i = target.indexOf(start);
    	int j = target.indexOf(end);
    	
    	if(i<0||j<0)
    		return "";
    	
    	result = target.substring(i+start.length(),j);
    	
    	return result;
    	
    }
    
    /** 
     * 根据参数格式获得对应日期 
     *  
     * @param  日期格式，例如yyyy-MM-dd，yyyy-MM-dd HH:mm:ss
     *  
     * @return 日期
     * @throws ParseException 
     * */  
    public static Date formatDate(String format) throws ParseException  
    {  
       Date currentTime = new Date();
       SimpleDateFormat formatter = new SimpleDateFormat(format); 
       String dateString = formatter.format(currentTime);
       
       SimpleDateFormat sdf=new SimpleDateFormat(format);
       Date cd=sdf.parse(dateString);
       ParsePosition pos = new ParsePosition(8);
       Date reDate = formatter.parse(dateString, pos); 
       return reDate; 
    }
    
    public static String getEntryStockNumber(Integer id){
    	StringBuilder sb = new StringBuilder("RKD");
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    	sb.append(sdf.format(new Date()));
    	sb.append(id);
    	return sb.toString();
    }
    
    public static String getPurchasePlanNumber(String baseNumber){
    	StringBuilder sb = new StringBuilder("CGJH");
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
    	sb.append(sdf.format(new Date()));
    	sb.append(baseNumber);
    	return sb.toString();
    }
    //判断字符串是否为数字
    public static boolean isNumeric(String str){
    	  for (int i = 0; i < str.length(); i++){
    	   if (!Character.isDigit(str.charAt(i))){
    	    return false;
    	   }
    	  }
    	  return true;
    }
    
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;
  
    /**
     * 修改颜色
     * @param matrix
     * @return
     */
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
          for (int y = 0; y < height; y++) {
            image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
          }
        }
        return image;
      }
    
    /**
     * 生成二维码
     * @param content
     * @return
     */
    public static BufferedImage generateQrCode(String content){ 
    	BufferedImage image = null;
        try {  
            
            QRCodeWriter writer = new QRCodeWriter();  
            //生成二维码  
            BitMatrix matrix = writer.encode(content, BarcodeFormat.QR_CODE,300,300);
            
            image = toBufferedImage(matrix);
            //image = MatrixToImageWriter.toBufferedImage(matrix);
            
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        finally{
        	return image;
        }
    }
    
    public static String getCellString(HSSFCell cell){
    
    	String text = "";
    	
    	switch(cell.getCellType()){
    	case HSSFCell.CELL_TYPE_BOOLEAN:
    		text = String.valueOf(cell.getBooleanCellValue());
    		break;
    	case HSSFCell.CELL_TYPE_NUMERIC:
    		text = String.valueOf(cell.getNumericCellValue());
    		break;
    	case HSSFCell.CELL_TYPE_STRING:
    		text = cell.getStringCellValue();
    		break;
    	default:
    		text = "";
    		break;
    	}
    	return text;
    }
}
